package flc.ast.fragment;

import static android.app.Activity.RESULT_OK;

import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.stark.cartoonavatarmaker.lib.core.AvatarDataProvider;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartBean;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartImportManager;
import com.stark.cartoonavatarmaker.lib.core.AvatarPartType;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.DressUpActivity;
import flc.ast.adapter.FormatPartAdapter;
import flc.ast.databinding.FragmentDressUpBinding;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.base.GeneralEvtDialog;

public class DressUpFragment extends BaseNoModelFragment<FragmentDressUpBinding> implements OnItemLongClickListener {

    private static final int REQ_IMPORT_AVATAR_PART = 1;
    private AvatarPartType mPartType;
    private FormatPartAdapter mAdapter;

    public static DressUpFragment newInstance(@NonNull AvatarPartType type) {
        DressUpFragment fragment = new DressUpFragment();
        fragment.mPartType = type;
        return fragment;
    }

    @Override
    protected int onCreate() {
        return R.layout.fragment_dress_up;
    }

    @Override
    protected void initView() {
        int spanCount = 3;
        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 4);
        mDataBinding.rvContainer.setLayoutManager(layoutManager);
        FormatPartAdapter partAdapter = new FormatPartAdapter(mPartType, spanCount);
        mAdapter = partAdapter;
        partAdapter.setOnItemClickListener(this);
        partAdapter.setOnItemLongClickListener(this);
        partAdapter.setNewInstance(loadData());
        mDataBinding.rvContainer.setAdapter(partAdapter);
    }

    @Override
    protected void initData() {
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        AvatarPartBean bean = mAdapter.getItem(position);
        if (mPartType == AvatarPartType.background && bean.getImgId() == R.drawable.ic_cam_add_72) {
            handleClickImport();
            return;
        }
        mAdapter.setSelPos(position);
        onSelAvatarPartBean(mAdapter.getItem(position));
    }

    @Override
    public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        AvatarPartBean partBean = mAdapter.getItem(position);
        if (partBean.isImport()) {
            showDelDialog(partBean);
            return true;
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQ_IMPORT_AVATAR_PART) {
            if (data == null) {
                return;
            }
            ToastUtils.showShort(R.string.bg_add_success_text);
            Uri importFileUri = data.getData();
            List<Uri> importUriList = new ArrayList<>();
            if (importFileUri != null) {
                //用户只选择了一个
                importUriList.add(importFileUri);
                handleImportAvatarPart(importUriList);
                return;
            }
            //用户选择了多个
            ClipData clipData = data.getClipData();
            if (clipData == null) {
                return;
            }
            for (int i = 0; i < clipData.getItemCount(); i++) {
                importUriList.add(clipData.getItemAt(i).getUri());
            }
            handleImportAvatarPart(importUriList);
        }
    }

    private void handleImportAvatarPart(List<Uri> importUriList) {
        List<AvatarPartBean> importBeans = new ArrayList<>();
        AvatarPartBean bean;
        for (Uri uri : importUriList) {
            bean = AvatarPartImportManager.createImportAvatarPartBean(mPartType, uri);
            importBeans.add(bean);
        }
        AvatarPartImportManager.getsInstance().addAvatarPartBeans(mPartType, importBeans);
        mAdapter.addData(mAdapter.getData().size() - 1, importBeans);
        mAdapter.notifyDataSetChanged();
    }

    public void handleClickImport() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); //允许选择多个文件
        startActivityForResult(intent, REQ_IMPORT_AVATAR_PART);
    }

    private void onSelAvatarPartBean(AvatarPartBean bean) {
        if (getActivity() instanceof DressUpActivity) {
            ((DressUpActivity) getActivity()).setAvatarPart(mPartType, bean);
        }
    }

    private List<AvatarPartBean> loadData() {
        List<AvatarPartBean> list = new ArrayList<>(AvatarDataProvider.getAvatarPart(mPartType));
        boolean canAddNone = false;
        switch (mPartType) {
            case background:
            case ear:
            case feature:
            case eyeFrame:
            case eyebrow:
            case glasses:
            case hair:
                canAddNone = true;
                break;
            default:
                break;
        }
        if (canAddNone) {
            list.add(0, new AvatarPartBean(R.drawable.ic_cam_none));
        }
        List<AvatarPartBean> importPartBeans = AvatarPartImportManager.getsInstance().getImportAvatarPartBeans(mPartType);
        if (importPartBeans != null) {
            list.addAll(importPartBeans);
        }
        if (mPartType == AvatarPartType.background) {
            list.add(new AvatarPartBean(R.drawable.ic_cam_add_72));
        }
        return list;
    }

    private void showDelDialog(AvatarPartBean bean) {
        new GeneralEvtDialog.Builder(getActivity())
                .content(getString(com.stark.common.res.R.string.sure_del_this_record))
                .rightBtnListener(v -> {
                    mAdapter.remove(bean);
                    AvatarPartImportManager.getsInstance().delAvatarPartBean(mPartType, bean);
                })
                .build()
                .show();
    }

}